package com.shaoshaohuo.app.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.webkit.WebSettings;

import com.google.gson.Gson;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.DetailsEntity;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/5/19.
 */

public class Okhttputils {
    private static final String TAG = "TAG";
//    private OkutListener okutListener;
    /**
     * 初始化变量，设置缓存文件夹及缓存大小
     */
    private static File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "cahe");
    private static Cache cache = new Cache(file, 10 * 1024 * 1024);
    private static OkHttpClient okHttpClient = new OkHttpClient.Builder().cache(cache).build();
    private static Okhttputils okhttputils;

    /*
              单例方法
     */
    public static Okhttputils Instanse(Context context) {
        if (okhttputils == null) {
            okhttputils = new Okhttputils();
        }
        return okhttputils;
    }


    //异步get请求
    public void getnet(Map<String, String> kv, Context context, String URL, final OkutListener okutListener, final Class<? extends BaseEntity> clx) {
        /**
         * 如果有网络我们请求最新数据,否则数据请求缓存，如果缓存没东西那就只能gg
         */
        Request.Builder builder = new Request.Builder();
        builder.url(URL);
        if (kv != null) {
            Set<Map.Entry<String, String>> entries = kv.entrySet();
            for (Map.Entry<String, String> a : entries) {
                String key = a.getKey();
                String value = a.getValue();
                builder.addHeader(key, value);
            }
        }

        if (isNetworkAvailable(context)) {
            deletcahe();
            Log.d(TAG, "getnet: 有网");
            builder.cacheControl(new CacheControl.Builder()
                    .maxAge(60, TimeUnit.SECONDS)
                    .build());
        } else {
            Log.d(TAG, "getnet: 无网 ");
            builder.cacheControl(CacheControl
                    .FORCE_CACHE);
        }
        Request build = builder.build();
        Call call = okHttpClient.newCall(build);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                okutListener.error(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Log.e("JSon", string);
                Log.e(TAG, "onResponse: " + string);
                if (string == null) {
//                    ViewPager viewPager;
//                    viewPager.setPageTra  nsformer();
                    okutListener.error(call, -1);
                    return;
                }

                BaseEntity o = new Gson().fromJson(string, BaseEntity.class);
                if (o != null && o.getCode() == 0) {
                    BaseEntity clx1 = new Gson().fromJson(string, clx);
                    okutListener.suseff(call, response, clx1);
                } else {
                    okutListener.error(call, o.getCode());
                }

            }
        });
    }

    /**
     * 检测当的网络（WLAN、3G/2G）状态
     *
     * @param context Context
     * @return true 表示网络可用
     */
    public boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 回调的接口
     */
    public interface OkutListener {
        void error(Call call, IOException e);

        void error(Call call, int code);

        void suseff(Call call, Response response, Object o);
    }

    /**
     * 为 了保留有网情况下最后一次数据，每次有网前清理一次缓存
     */
    public void deletcahe() {
        if (file.exists()) {
            File[] files = file.listFiles();
            for (File f : files) {
                f.delete();
            }
        }
    }

    /**
     * post 提交表单
     */
    public void postFromBody(Map<String, String> head, final String Url, Map<String, String> kv, final OkutListener okutListener, final Class<? extends BaseEntity> cls) {
        FormBody.Builder builder = new FormBody.Builder();
        Set<Map.Entry<String, String>> entries = kv.entrySet();
        for (Map.Entry<String, String> a : entries) {
            String key = a.getKey();
            String value = a.getValue();
            if (key != null && value != null) {
                builder.add(key, value);
            }

        }

        Request.Builder build = new Request.Builder()
                .cacheControl(
                        CacheControl.FORCE_NETWORK
                )
                .url(Url).post(builder.build());

        if (head != null) {
            Set<Map.Entry<String, String>> entriesa = head.entrySet();
            for (Map.Entry<String, String> a : entriesa) {
                String key = a.getKey();
                String value = a.getValue();
                build.addHeader(key, value);
            }
        }
        Request build1 = build.build();

        Call call = okHttpClient.newCall(build1);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                okutListener.error(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Log.e(TAG, "url-" + Url + "======onResponse: " + string);
                Gson gson = new Gson();
                BaseEntity o = gson.fromJson(string, BaseEntity.class);
                if (o != null) {
                    int code = o.getCode();
                    if (code == 0) {
                        BaseEntity baseEntity = gson.fromJson(string, cls);
                        okutListener.suseff(call, response, baseEntity);
                    } else {
                        okutListener.error(call, code);
                    }

                } else {
                    okutListener.error(call, new IOException(""));
                }

            }
        });
    }

    /**
     * post提交字符串
     */
    public void poststring(String Url, String kv, final OkutListener okutListener, final Class<? extends BaseEntity> cls) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/utf-8"), kv);
        //暂时不用
        DetailsEntity.DataBean dataBean = new DetailsEntity.DataBean();

//        "" '"" 0 '
        String s = new Gson().toJson(dataBean);
    }

    /**
     * 上传图片
     */


    public void upImge(String Url, Map<String, String> head, Map<String, String> kv, String nane, File file, final OkutListener okutListener, final Class<? extends Object> cls) {
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        if (kv != null) {
            Set<Map.Entry<String, String>> entries = kv.entrySet();
            for (Map.Entry<String, String> a : entries) {
                String key = a.getKey();
                String value = a.getValue();
                builder.addFormDataPart(key, value);
            }
        }

        builder.addFormDataPart(nane, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
        MultipartBody build = builder.build();

        Request request;
        Request.Builder builder1 = new Request.Builder();
        if (head != null) {
            Set<Map.Entry<String, String>> entries = head.entrySet();
            for (Map.Entry<String, String> a : entries) {
                String key = a.getKey();
                String value = a.getValue();
                builder1.addHeader(key, value);
            }

        }

        request = builder1
                .url(Url)
                .post(build)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                okutListener.error(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Gson gson = new Gson();
                Log.e(TAG, "onResponse: " + string);
                BaseEntity o = (BaseEntity) gson.fromJson(string, cls);
                if (o.getCode() == 0) {
                    okutListener.suseff(call, response, o);
                } else {
                    okutListener.error(call, o.getCode());
                }

            }
        });
    }

    /**
     * 文件上传
     */
    private static final MediaType STREAM = MediaType.parse("application/octet-stream");
    public void upfile(String Url, Map<String, String> kv, String nane, File file, final OkutListener okutListener, final Class<? extends Object> cls) {
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        Set<Map.Entry<String, String>> entries = kv.entrySet();
        for (Map.Entry<String, String> a : entries) {
            String key = a.getKey();
            String value = a.getValue();
            builder.addFormDataPart(key, value);
        }
        builder.addFormDataPart(nane, file.getName(), RequestBody.create(STREAM, file));
        MultipartBody build = builder.build();
        Request request = new Request.Builder()
                .cacheControl(
                        CacheControl.FORCE_NETWORK

                )
                .url(Url)
                .post(build)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                okutListener.error(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Gson gson = new Gson();
                Object o = gson.fromJson(string, cls);
                okutListener.suseff(call, response, o);
            }
        });
    }

    public void addhead(Map<String, String> m, final String url, final OkutListener okutListener, final Class<? extends Object> cls) {
        FormBody build = new FormBody.Builder().build();
        Request.Builder url1 = new Request.Builder().url(url).post(build);
        Set<Map.Entry<String, String>> entries = m.entrySet();
        for (Map.Entry<String, String> a : entries) {
            String key = a.getKey();
            String value = a.getValue();
            url1.addHeader(key, value);
        }
        Call call = okHttpClient.newCall(url1.build());
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                okutListener.error(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Log.d(TAG, "onResponse: " + string + "url" + url);
                Gson gson = new Gson();
                Object o = gson.fromJson(string, cls);
                okutListener.suseff(call, response, o);
            }
        });
    }


    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    /**
     * 多图上传
     *
     * @param Url
     * @param filesome
     * @param head
     * @param kv
     * @param okutListener
     * @param cls
     */
    public void upImgesomes(Context context, String Url, List<File> filesome, Map<String, String> head, Map<String, String> kv, final OkutListener okutListener, final Class<? extends Object> cls) {
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        if (kv != null) {
            Set<Map.Entry<String, String>> entries = kv.entrySet();
            for (Map.Entry<String, String> a : entries) {
                String key = a.getKey();
                String value = a.getValue();
                builder.addFormDataPart(key, value);
            }
        }
        if (filesome != null) {
            for (int i = 0; i < filesome.size(); i++) {
                File file = filesome.get(i);
                builder.addFormDataPart("file[]", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
            }
        }

        MultipartBody build = builder.build();
        Request request;
        Request.Builder builder1 = new Request.Builder();
        if (head != null) {
            Set<Map.Entry<String, String>> entries = head.entrySet();
            for (Map.Entry<String, String> a : entries) {
                String key = a.getKey();
                String value = a.getValue();
                builder1.addHeader(key, value);
            }
        }

        request = builder1
                .url(Url)
                .post(build)
                .removeHeader("User-Agent")
                .addHeader("User-Agent", getUserAgent(context))
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                okutListener.error(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Log.e("退款", string);
                Gson gson = new Gson();
                BaseEntity o = (BaseEntity) gson.fromJson(string, cls);
                if (o.getCode() == 0) {
                    okutListener.suseff(call, response, o);
                } else {
                    okutListener.error(call, o.getCode());
                }

            }
        });
    }

    private String getUserAgent(Context context) {
        String userAgent = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            try {
                userAgent = WebSettings.getDefaultUserAgent(context);
            } catch (Exception e) {
                userAgent = System.getProperty("http.agent");
            }
        } else {
            userAgent = System.getProperty("http.agent");
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0, length = userAgent.length(); i < length; i++) {
            char c = userAgent.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", (int) c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

}
